package com.turbo.service.impl;

import com.esotericsoftware.yamlbeans.YamlException;
import com.esotericsoftware.yamlbeans.YamlReader;
import com.intellij.openapi.progress.PerformInBackgroundOption;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.turbo.pojo.Demo;
import com.turbo.service.ProjectService;
import com.turbo.config.FreeMarkerConfig;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.temporal.ChronoField;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: zwx
 * @time: 2021/3/20 18:01
 */
public class ProjectServiceImpl implements ProjectService {

    private String time = null;

    @Override
    public String doSomething(Project project, String dir, String name) {
        System.out.println(dir);
        System.out.println(name);
        // 开启后台进度条，即右下方
        /*ProgressManager.getInstance().run(new Task.Backgroundable(project, "正在创建"+name+".txt文件"){
            @Override
            public void run(@NotNull ProgressIndicator progressIndicator){
                String fileName = name + ".txt";
                progressIndicator.setIndeterminate(false);
                progressIndicator.setFraction(0.10);
                progressIndicator.setText("10%");
                String filePath = dir + "/" + fileName;
                try{
                    File file = new File(filePath);
                    if (!file.exists()){
                        file.createNewFile();
                    }
                    progressIndicator.setFraction(0.50);
                    progressIndicator.setText("50%");
                    FileWriter writer = new FileWriter(file);
                    writer.write("testtest");
                    writer.flush();
                    progressIndicator.setFraction(0.90);
                    progressIndicator.setText("90%");
                    writer.close();
                    progressIndicator.setFraction(1.00);
                    progressIndicator.setText("100%");

                    // 重新从磁盘中加载创建的文件
                    VirtualFile virtualFile = VfsUtil.findFileByIoFile(file, true);
                    if (virtualFile != null) {
                        virtualFile.refresh(true, false);
                    }
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        });*/

        // 开启进度条弹框
        final int[] i = {0};
        ProgressManager.getInstance().run(new Task.ConditionalModal(project, "正在创建" + name + ".txt文件", false, PerformInBackgroundOption.DEAF) {
            @Override
            public void run(@NotNull ProgressIndicator progressIndicator) {
                String fileName = name + ".txt";
                progressIndicator.setIndeterminate(false);
                progressIndicator.setFraction(0.10);
                // progressIndicator.setText("10%");
                String filePath = dir + "/" + fileName;
                try {
                    Thread.sleep(1000);
                    File file = new File(filePath);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    progressIndicator.setFraction(0.50);
                    Thread.sleep(1000);
                    FileWriter writer = new FileWriter(file);
                    writer.write("testtest");
                    writer.flush();
                    progressIndicator.setFraction(0.90);
                    Thread.sleep(1000);
                    writer.close();
                    progressIndicator.setFraction(1.00);
                    // 重新从磁盘中加载创建的文件
                    VirtualFile virtualFile = VfsUtil.findFileByIoFile(file, true);
                    if (virtualFile != null) {
                        virtualFile.refresh(true, false);
                    }
                } catch (Exception e) {
                    i[0]++;
                }
            }
        });
        if (i[0] != 0) {
            return StringUtils.EMPTY;
        } else {
            return name;
        }
    }

    @Override
    public String doSomething() {
        if (time == null) {
            LocalTime localTime = LocalTime.now();
            time = "Project实例创建时间=" + localTime.get(ChronoField.HOUR_OF_DAY) + ":" + localTime.get(ChronoField.MINUTE_OF_HOUR) + ":" + localTime.get(ChronoField.SECOND_OF_MINUTE);
        }
        return time;
    }

    /**
     * 方案1：把值全部提出来放入list集合，多线程去取list集合并创建文件
     *
     * @param project
     * @param dir
     */
    @Override
    public boolean readYml(Project project, String dir, String packDir) {
        System.out.println("========= : " + dir);
        System.out.println("---------: " + packDir);
        if (!packDir.endsWith("src\\main\\java")) {
            int index = packDir.lastIndexOf("src\\main\\java");
            if (index == -1) {
                return false;
            }
            String[] ifile = packDir.substring(index + 14).split("\\\\");
            StringBuilder sb = new StringBuilder("package ");
            for (String str : ifile) {
                sb.append(str).append(".");
            }
            String packageN = sb.substring(0, sb.length() - 1);
            System.out.println(packageN);
            grow(packageN, packDir);
        }

        // 获取yaml中的内容
        String[] typeArry;
        YamlReader reader = null;
        try {
            reader = new YamlReader(new FileReader(dir));
            Map<String, Object> map = (Map) reader.read();
            for (Map.Entry<String, Object> rootEntry : map.entrySet()) {
                System.out.println(rootEntry.getKey() + ": ");
                Map<String, Object> itemMap = (Map) rootEntry.getValue();
                String typeVal = (String) itemMap.get("type");
                if (StringUtils.isNotBlank(typeVal)) {
                    String newType = typeVal.replace(" ", "");
                    typeArry = newType.split(",");
                    System.out.println(typeVal);
                    Map<String, Object> valueMap = (Map) itemMap.get("item");
                    for (Map.Entry<String, Object> value : valueMap.entrySet()) {
                        System.out.println(value.getKey() + ": ");
                        System.out.println(value.getValue());
                    }
                }
            }
        } catch (FileNotFoundException | YamlException e) {
            e.printStackTrace();
        }

        return true;
    }

    /**
     * 生成java文件
     *
     * @param packageN
     */
    private void grow(String packageN, String packDir) {
        ClassLoader classLoader = ProjectServiceImpl.class.getClassLoader();
        InputStream resourceAsStream = classLoader.getResourceAsStream("vm/demo.vm");
        System.out.println(resourceAsStream);
        try {
            FreeMarkerConfig hf = new FreeMarkerConfig();
            hf.init();
            HashMap<String, Object> map = new HashMap<>();
            map.put("pack", packageN);
            map.put("dateFlag", false);
            map.put("describe", "这是描述");
            map.put("author", "Turbo");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            map.put("dateTime", format.format(new Date()));
            map.put("enumName", "DemoEnum");
            ArrayList<Demo> demoList = new ArrayList<>();
            demoList.add(new Demo("DEMO_A", "1", "false"));
            demoList.add(new Demo("DEMO_B", "2", "true"));
            demoList.add(new Demo("DEMO_C", "3", "true"));
            map.put("listItem", demoList);
            map.put("pTypeOne", "Integer");
            map.put("pTypeTwo", "Boolean");
            map.put("aliaEN", "demoEnum");
            packDir = packDir.substring(13);
            hf.process(map.get("enumName") + ".java", map, hf, packDir, "demo.ftl");
            // 从内存加载
            File file = new File(packDir + "\\" + map.get("enumName") + ".java");
            VirtualFile virtualFile = VfsUtil.findFileByIoFile(file, true);
            if (virtualFile != null) {
                virtualFile.refresh(true, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
